<?
/**
 *
 * Copyright (C) 2003-2011 Cory Powers
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 */
require_once('SI_TaskActivity.php');

////////////////////////////////////////////////////////////
// Code generated by CodeGen (http://uversaconsulting.net).
// Insert custom code where indicated below.
////////////////////////////////////////////////////////////

// SI_Check Class Definition
////////////////////////////////////////////////////////////
class SI_Check{
	var $id, $user_id, $type, $number,
	  $name, $address1, $address2, $city,
	  $state, $zip, $description, $amount,
	  $timestamp, $trans_id;

	var $_ut;
	
	var $error;

	function SI_Check(){
		$this->error = '';
		$this->id = 0;
		$this->user_id = 0;
		$this->type = '';
		$this->number = 0;
		$this->name = '';
		$this->address1 = '';
		$this->address2 = '';
		$this->city = '';
		$this->state = '';
		$this->zip = '';
		$this->description = '';
		$this->amount = 0;
		$this->timestamp = 0;
		$this->trans_id = 0;

		$this->_ut = FALSE;
	}

	function _populateData($values){
		if(is_array($values)){
			$this->id = $values[0];
			$this->user_id = $values[1];
			$this->type = $values[2];
			$this->number = $values[3];
			$this->name = $values[4];
			$this->address1 = $values[5];
			$this->address2 = $values[6];
			$this->city = $values[7];
			$this->state = $values[8];
			$this->zip = $values[9];
			$this->description = $values[10];
			$this->amount = $values[11];
			$this->timestamp = $values[12];
			$this->trans_id = $values[13];
		}
	}

	function updateFromAssocArray($array){
		if(isset($array['id'])) $this->id = $array['id'];
		if(isset($array['user_id'])) $this->user_id = $array['user_id'];
		if(isset($array['type'])) $this->type = $array['type'];
		if(isset($array['number'])) $this->number = $array['number'];
		if(isset($array['name'])) $this->name = $array['name'];
		if(isset($array['address1'])) $this->address1 = $array['address1'];
		if(isset($array['address2'])) $this->address2 = $array['address2'];
		if(isset($array['city'])) $this->city = $array['city'];
		if(isset($array['state'])) $this->state = $array['state'];
		if(isset($array['zip'])) $this->zip = $array['zip'];
		if(isset($array['description'])) $this->description = $array['description'];
		if(isset($array['amount'])) $this->amount = $array['amount'];
		if(isset($array['timestamp'])) $this->timestamp = $array['timestamp'];
		if(isset($array['trans_id'])) $this->trans_id = $array['trans_id'];
	}

	function escapeStrings(){
		global $db_conn;

		$vars = get_object_vars($this);
		foreach($vars as $key => $value){
			if(is_string($value)){
				$this->$key = $db_conn->escapeString($value);
			}
		}
	}

	function stripSlashes(){
		$vars = get_object_vars($this);
		foreach($vars as $key => $value){
			if(is_string($value)){
				$this->$key = stripcslashes($value);
			}
		}
	}

	function getLastError(){
		return $this->error;
	}

	function add(){
		global $db_conn;

		$this->escapeStrings();
		$result = $db_conn->query("INSERT INTO checks (user_id, type, number, name, ".
		  "address1, address2, city, state, ".
		  "zip, description, amount, timestamp, ".
		  "trans_id)".
		  " VALUES(".$this->user_id.", '".$this->type."', ".$this->number.", '".$this->name."', ".
		  "'".$this->address1."', '".$this->address2."', '".$this->city."', '".$this->state."', ".
		  "'".$this->zip."', '".$this->description."', ".$this->amount.", ".$this->timestamp.", ".
		  "".$this->trans_id.")");
		$this->stripSlashes();
		if($result){
			$this->id = mysql_insert_id($db_conn->_conn);
			return TRUE;
		}else{
			$this->error = "SI_Check::add() : ".$db_conn->getLastError()."\n";
			return FALSE;
		}
	}

	function update(){
		global $db_conn;

		if(!isset($this->id)){
			$this->error = "SI_Check::update() : Check id not set\n";
			return FALSE;
		}

		$this->escapeStrings();
		$result = $db_conn->query("UPDATE checks SET user_id = ".$this->user_id.", ".
		  "type = '".$this->type."', number = ".$this->number.", ".
		  "name = '".$this->name."', address1 = '".$this->address1."', ".
		  "address2 = '".$this->address2."', city = '".$this->city."', ".
		  "state = '".$this->state."', zip = '".$this->zip."', ".
		  "description = '".$this->description."', amount = ".$this->amount.", ".
		  "timestamp = ".$this->timestamp.", trans_id = ".$this->trans_id."".
		  " WHERE id = ".$this->id."");
		$this->stripSlashes();
		if($result){
			return TRUE;
		}else{
			$this->error = "SI_Check::update() : ".$db_conn->getLastError()."\n";
			return FALSE;
		}
	}

	function delete($id = NULL){
		global $db_conn;

		if(!isset($id)){
			$id = $this->id;
		}

		if(!isset($id)){
			$this->error = "SI_Check::delete() : Check id not set\n";
			return FALSE;
		}

		$result = $db_conn->query("DELETE FROM checks WHERE id = $id");

		if($result){
			return TRUE;
		}else{
			$this->error = "SI_Check::delete() : ".$db_conn->getLastError()."\n";
			return FALSE;
		}
	}

	function get($id = NULL){
		global $db_conn;

		if(!isset($id)){
			$id = $this->id;
		}

		if(!isset($id)){
			$this->error = "SI_Check::get() : Check id not set\n";
			return FALSE;
		}

		$Check = SI_Check::retrieveSet("WHERE id = $id", TRUE);
		if($Check === FALSE){
			return FALSE;
		}

		if(isset($Check[0])){
			$this->_populateData($Check[0]);
			if($this->_populateCommTransactions() === FALSE)
				return FALSE;
			if($this->_populateCostTransactions() === FALSE)
				return FALSE;
			$this->stripSlashes();
		}else{
			$this->error = "SI_Check::get() : No data retrieved from query\n";
			return FALSE;
		}
		return TRUE;
	}

	function retrieveSet($clause = '', $raw = FALSE){
		global $db_conn;

		if(!empty($clause)){
			$clause = trim($clause);
			if(strlen($clause) > 5){
				if(strtolower(substr($clause, 0, 5)) != "where" && strtolower(substr($clause, 0, 5)) != "order")
					$clause = "WHERE ".$clause;
			}else{
				$clause = "WHERE ".$clause;
			}
		}

		$result = $db_conn->query("SELECT  id, user_id, type, number, name, address1, ".
		  "address2, city, state, zip, description, amount, ".
		  "timestamp, trans_id".
		  " FROM checks ".$clause);

		if(!$result){
			$this->error = "SI_Check::retrieveSet(): ".$db_conn->getLastError()."\n";
			return FALSE;
		}

		while($row=$result->fetchRow()){
			if($raw == TRUE){
				$Check[] = $row;
			}else{
				$temp =& new SI_Check();
				$temp->_populateData($row);
				$Check[] =& $temp;
			}

		}

		return $Check;
	}
// BEGIN - Custom SI_Check methods
////////////////////////////////////////////////////////////
	var $_cost_transaction_ids;
	var $_comm_transaction_ids;

	function getTypeSelectTags($selected = NULL){
		$tags = "";

		$options = array( 'CHECK' => 'CHECK', 'EFT' => 'EFT', 'CC' => 'CC' );

		foreach($options as $value => $name){
			$sel_text = "";
			if($value==$selected)
				$sel_text = " SELECTED";

			$tags .= "<OPTION VALUE=\"".$value."\"".$sel_text.">".$name." ".$row[2]."</OPTION>\n";
		}
		return $tags;
	}

	function _populateCostTransactions(){
		global $db_conn;

		$result = $db_conn->query("SELECT trans_id FROM check_transactions WHERE type = 'COST' AND check_id = ".intval($this->id));
		if($result === FALSE){
			$this->error = "SI_Check::_populateTransactions(): Error getting transaction ids: ".$db_conn->getLastError();
			return FALSE;
		}

		$this->_cost_transaction_ids = array();
		while($row = $result->fetchArray()){
			$this->_cost_transaction_ids[] = $row['trans_id'];
		}

		return TRUE;
	}

	function _populateCommTransactions(){
		global $db_conn;

		$result = $db_conn->query("SELECT trans_id FROM check_transactions WHERE type = 'COMM' AND check_id = ".intval($this->id));
		if($result === FALSE){
			$this->error = "SI_Check::_populateTransactions(): Error getting transaction ids: ".$db_conn->getLastError();
			return FALSE;
		}

		$this->_comm_transaction_ids = array();
		while($row = $result->fetchArray()){
			$this->_comm_transaction_ids[] = $row['trans_id'];
		}

		return TRUE;
	}

	function attachCostTransactions($trans_ids, $append = FALSE){
		global $db_conn;

		if(!$append)
			if($this->clearCostTransactions() === FALSE)
				return FALSE;

		if(count($trans_ids) == 0)
			return TRUE;

		foreach($trans_ids as $id){
			$id = intval($id);
			if($id > 0){
				$sql = "INSERT INTO check_transactions SET type = 'COST', check_id = ".intval($this->id).", trans_id = $id";
				$result = $db_conn->query($sql);
				if($result === FALSE){
					$this->error = "SI_Check::attachTransactions(): Error adding transaction id $id: ".$db_conn->getLastError();
					return FALSE;
				}
			}
		}

		return TRUE;
	}

	function clearCostTransactions(){
		global $db_conn;

		$sql = "DELETE FROM check_transactions WHERE type = 'COST' AND check_id = ".intval($this->id);
		$result = $db_conn->query($sql);
		if($result === FALSE){
			$this->error = "SI_Check::clearCostTransactions(): Error removing transactions: ".$db_conn->getLastError();
			return FALSE;
		}

	}

	function attachCommTransactions($trans_ids, $append = FALSE){
		global $db_conn;

		if(!$append)
			if($this->clearCommTransactions() === FALSE)
				return FALSE;

		if(count($trans_ids) == 0)
			return TRUE;

		foreach($trans_ids as $id){
			$id = intval($id);
			if($id > 0){
				$sql = "INSERT INTO check_transactions SET type = 'COMM', check_id = ".intval($this->id).", trans_id = $id";
				$result = $db_conn->query($sql);
				if($result === FALSE){
					$this->error = "SI_Check::attachCommTransactions(): Error adding transaction id $id: ".$db_conn->getLastError();
					return FALSE;
				}
			}
		}

		return TRUE;
	}

	function clearCommTransactions(){
	    global $db_conn;
	
		$sql = "DELETE FROM check_transactions WHERE type = 'COMM' AND check_id = ".intval($this->id);
		$result = $db_conn->query($sql);
		if($result === FALSE){
			$this->error = "SI_Check::clearCommTransactions(): Error removing transactions: ".$db_conn->getLastError();
			return FALSE;
		}
	}

	function _getUserTrans(){
		$trans_id = intval($this->trans_id);
		if($trans_id <= 0)
			return TRUE;
			
		if($this->_ut == FALSE){
			$ut = new SI_UserTransaction();
			if($ut->get($trans_id) === FALSE){
				$this->error = "Error getting linked transaction: ".$ut->getLastError();
				return FALSE;	
			}
			$this->_ut = &$ut;
		}
		
		return TRUE;
	}
	
	function getDescription(){
		if($this->_getUserTrans() === FALSE)
			return FALSE;
		
		return $this->_ut->description;	
	}

	function getByNumber($number){
		$Check = SI_Check::retrieveSet("WHERE number = '$number'", TRUE);
		if($Check === FALSE){
			return FALSE;
		}

		if(isset($Check[0])){
			$this->_populateData($Check[0]);
			if($this->_populateCommTransactions() === FALSE)
				return FALSE;
			if($this->_populateCostTransactions() === FALSE)
				return FALSE;
			$this->stripSlashes();
		}else{
			$this->error = "SI_Check::getByNumber() : No data retrieved from query\n";
			return FALSE;
		}
		return TRUE;
	}

	function getActivities(){
		global $db_conn;
		
		if($this->id <= 0)
			return array();
			
		$sql = "
			SELECT  a.id, a.task_id, a.user_id, a.text, a.start_ts, a.end_ts,
			a.hourly_cost, a.hourly_rate, a.cost_trans_id, a.com_trans_id, a.invoice_id, a.sales_com_type_id,
			t.name, c.name, p.name, ct.check_id AS check_id, p.name AS project_name,
			t.name AS task_name, ut.amount AS cost, 
			ROUND((((a.end_ts - a.start_ts) / 60 / 60) * a.hourly_rate), 2) AS price
			FROM task_activities AS a
			LEFT JOIN tasks AS t ON a.task_id = t.id
			LEFT JOIN projects AS p ON t.project_id = p.id
			LEFT JOIN companies AS c ON p.company_id = c.id
			LEFT JOIN user_transactions AS ut ON a.cost_trans_id = ut.id
			LEFT JOIN check_transactions AS ct ON a.cost_trans_id = ct.trans_id
			LEFT JOIN checks AS chk ON chk.id = ct.check_id
			WHERE chk.id = '$this->id'
		";

		$result = $db_conn->query($sql);

	  	if($result === FALSE){
	  		$this->error = "SI_Check::getActivities(): ".$db_conn->getLastError()."\n";
			return FALSE;
		}
		
		$activities = array();
		while($row=$result->fetchArray(MYSQL_ASSOC)){
			$temp =& new SI_TaskActivity();
			$temp->updateFromAssocArray($row);
			if($temp->calculate() === FALSE){
				$this->error = "SI_Check::getActivities(): Error calculating activity amounts: " . $temp->getLastError();
				return FALSE;	
			}
			$temp->cost_paid = (intval($row['cost_check_id']) > 0 ? TRUE : FALSE);
			$activities[] =& $temp;
		}

		return $activities;
	}

	function getCommissions($id, $unpaid = TRUE){
		global $db_conn;

		if($this->id <= 0)
			return array();

		$sql = "
			SELECT  a.id, a.task_id, a.user_id, a.text, a.start_ts, a.end_ts,
			a.hourly_cost, a.hourly_rate, a.cost_trans_id, a.com_trans_id, a.invoice_id, a.sales_com_type_id,
			t.name, c.name, p.name, ct.check_id AS check_id, p.name AS project_name,
			t.name AS task_name, ut.amount AS cost, 
			ROUND((((a.end_ts - a.start_ts) / 60 / 60) * a.hourly_rate), 2) AS price
			FROM task_activities AS a
			LEFT JOIN tasks AS t ON a.task_id = t.id
			LEFT JOIN projects AS p ON t.project_id = p.id
			LEFT JOIN companies AS c ON p.company_id = c.id
			LEFT JOIN user_transactions AS ut ON a.com_trans_id = ut.id
			LEFT JOIN check_transactions AS ct ON a.com_trans_id = ct.trans_id
			LEFT JOIN checks AS chk ON chk.id = ct.check_id
			WHERE chk.id = '$this->id'
		";

		$result = $db_conn->query($sql);

	  	if($result === FALSE){
	  		$this->error = "SI_Check::getActivities(): ".$db_conn->getLastError()."\n";
			return FALSE;
		}
		
		$activities = array();
		while($row=$result->fetchArray(MYSQL_ASSOC)){
			$temp =& new SI_TaskActivity();
			$temp->updateFromAssocArray($row);
			if($temp->calculate() === FALSE){
				$this->error = "SI_Check::getCommissions(): Error calculating activity amounts: " . $temp->getLastError();
				return FALSE;	
			}
			$activities[] =& $temp;
		}

		return $activities;
	}

// END - Custom SI_Check methods
////////////////////////////////////////////////////////////
}

